package cn.net.chenbao.medical;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.net.chenbao.medical.adapter.radapter.CommonViewHolder;
import cn.net.chenbao.medical.adapter.radapter.RvCommonAdapter;
import cn.net.chenbao.medical.base.BaseActivity;
import cn.net.chenbao.medical.bean.Report;
import cn.net.chenbao.medical.mvp.ReportP;
import cn.net.chenbao.medical.mvp.presenter.IReportP;
import cn.net.chenbao.medical.mvp.view.IReportV;
import cn.net.chenbao.medical.util.Consts;
import cn.net.chenbao.medical.util.TimeUtil;
import cn.net.chenbao.medical.util.ZLog;

public class ReportListActivity extends BaseActivity implements View.OnClickListener, IReportV {
    private int mMode;
    private int mPyFlag;
    private long mPrintId;
    private TextView mTvLeft, mTvTitle, mTvRight;
    private String mStartDate, mEndDate;
    private Calendar mSelectCalendar;

    private TimePickerView mTimePV;
    private IReportP mReportP;

    private RecyclerView mRvReport;
    private RvCommonAdapter mReportAdapter;
    private List<Report> mReports;

    private LinearLayout mLlAbnormal;
    private int position;
    LinearLayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_list);
        mReportP = new ReportP(this);
        InitTitle();
        InitView();
    }

    private void InitTitle() {
        mMode = getIntent().getIntExtra(Consts.KEY_MODULE, -1);
        mStartDate = getIntent().getStringExtra("startDate");
        findViewById(R.id.iv_left).setOnClickListener(this);
        findViewById(R.id.tv_abnormal).setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_center);
        mTvRight = (TextView) findViewById(R.id.tv_date_select);
        mLlAbnormal = (LinearLayout) findViewById(R.id.ll_abnormal);
        mTvRight.setText("查询");
        mTvRight.setOnClickListener(this);
        switch (mMode) {
            case Consts.MODE_JC:
                //进仓报表
                mTvTitle.setText(getString(R.string.in_report));
                mPrintId = getIntent().getLongExtra("printId", -1);
                break;
            case Consts.MODE_NURSE:
                //配液报表
                mTvTitle.setText(getString(R.string.py_report));
                mPrintId = getIntent().getLongExtra("printId", -1);
                break;
            case Consts.MODE_KBCC:
            case Consts.MODE_APOTHECARY:
                //出仓报表
                mTvTitle.setText(getString(R.string.out_report));
                mPrintId = getIntent().getLongExtra("printId", -1);
                break;
            case Consts.MODE_HSJJ:
                //交接报表
                mTvTitle.setText(getString(R.string.jiao_report));
                mPyFlag = getIntent().getIntExtra("pyFlag", -1);
                break;
            case Consts.MODE_BB:
                //所有报表
                mTvRight.setVisibility(View.GONE);
                mTvTitle.setText(getString(R.string.report));
                mEndDate = getIntent().getStringExtra("endDate");
                mPyFlag = getIntent().getIntExtra("pyFlag", -1);
                mLlAbnormal.setVisibility(View.GONE);
                break;
        }
    }

    private void InitView() {
        mRvReport = (RecyclerView) findViewById(R.id.rv_report);
        mLayoutManager = new LinearLayoutManager(this);

        mRvReport.setLayoutManager(mLayoutManager);
        mReports = new ArrayList<>();
        mReportAdapter = new RvCommonAdapter<Report>(this, mReports, R.layout.report_item) {
            @Override
            public void convert(CommonViewHolder holder, Report report) {
                if (TextUtils.isEmpty(report.AutoPyjName)) {
                    holder.getView(R.id.ll_Pyj).setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.ll_Pyj).setVisibility(View.VISIBLE);
                    //新增配液间显示（进仓报表与出仓报表）
                    holder.setText(R.id.tv_Pyj, String.format(getString(R.string.report_Pyj), report.AutoPyjName + ""));
                }

                if (TextUtils.isEmpty(report.KsName)) {
                    holder.getView(R.id.ll_ksmc).setVisibility(View.GONE);
                } else {
                    //更改去除科室信息
                    holder.getView(R.id.ll_ksmc).setVisibility(View.VISIBLE);
                    holder.setText(R.id.tv_KsName, String.format(getString(R.string.report_KsName), TextUtils.isEmpty(report.KsName) ? "" : report.KsName));
                    holder.setText(R.id.tv_Ksmc, String.format(getString(R.string.report_Ksmc), TextUtils.isEmpty(report.Ksmc) ? "" : report.Ksmc));
                }

                holder.setText(R.id.tv_Bz, String.format(getString(R.string.report_bz), TextUtils.isEmpty(report.Bz) ? "" : report.Bz));

                holder.setText(R.id.tv_Rq, String.format(getString(R.string.report_rq), TextUtils.isEmpty(report.Rq) ? "" : TimeUtil.timeToData(report.Rq)));
                holder.setText(R.id.tv_Printid, String.format(getString(R.string.report_printid), report.Printid + ""));

                holder.setText(R.id.tv_Cczs, String.format(getString(R.string.report_Cczs), report.Cczs + ""));
                holder.setText(R.id.tv_Hsjjzs, String.format(getString(R.string.report_Hsjjzs), report.Hsjjzs + ""));
                holder.setText(R.id.tv_Jczs, String.format(getString(R.string.report_Jczs), report.Jczs + ""));
                holder.setText(R.id.tv_Pyzs, String.format(getString(R.string.report_Pyzs), report.Pyzs + ""));
                holder.setText(R.id.tv_Syzs, String.format(getString(R.string.report_Syzs), report.Syzs + ""));

            }
        };
        mRvReport.setAdapter(mReportAdapter);

        mReportP.doQuery(mMode, mStartDate, mEndDate, mPyFlag, mPrintId);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left: {
                finish();
                break;
            }
            case R.id.tv_date_select:
                showTimePicker();
                break;
            case R.id.tv_abnormal:
                intent(mMode);
                break;
        }
    }


    @Override
    public void showTimePicker() {
        if (mTimePV == null) {
            mSelectCalendar = Calendar.getInstance();

            //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
            //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
            Calendar startDate = Calendar.getInstance();
            startDate.set(mSelectCalendar.get(Calendar.YEAR) - 5, 0, 1);
            Calendar endDate = Calendar.getInstance();
            endDate.set(mSelectCalendar.get(Calendar.YEAR) + 3, 11, 30);
            //时间选择器
            mTimePV = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {//选中事件回调
                    // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null

                }
            })
                    //年月日时分秒 的显示与否，不设置则默认全部显示
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("", "月", "日", "", "", "")
                    .isCenterLabel(false)
                    .setDividerColor(ContextCompat.getColor(ReportListActivity.this, R.color.main_line_color))
                    .setContentSize(15)
                    .setTitleSize(13)
                    .setDate(mSelectCalendar)
                    .setRangDate(startDate, endDate)
                    .setBgColor(0xFFFFFFFF)
                    .setTitleBgColor(0xFFFFFFFF)
                    .setSubCalSize(15)
                    .setCancelText("取消")
                    .setSubmitColor(ContextCompat.getColor(ReportListActivity.this, R.color.main_color))
                    .setCancelColor(ContextCompat.getColor(ReportListActivity.this, R.color.black))
                    .setTextColorOut(ContextCompat.getColor(ReportListActivity.this, R.color.black2))
                    .setTextColorCenter(ContextCompat.getColor(this, R.color.main_color)) //设置选中项文字颜色
                    .setDecorView(null)
                    .build();
            mTimePV.setTitleText("选择日期");
        }
        mTimePV.show();
    }

    @Override
    public void QuerySuccess(List<Report> reports) {
        this.mReports = reports;
        mReportAdapter.setDatas(mReports);
        mReportAdapter.notifyDataSetChanged();
    }

    private Intent mIntent;

    private void intent(int mode) {
        mIntent = mIntent == null ? new Intent(this, AbnormalActivity.class) : mIntent;
        mIntent.putExtra(Consts.KEY_MODULE, mode);
        switch (mode) {
            case Consts.MODE_NURSE:
            case Consts.MODE_JC:
            case Consts.MODE_KBCC:
            case Consts.MODE_APOTHECARY:
                //进仓报表
                mIntent.putExtra("startDate", mStartDate);
                mIntent.putExtra("printId", mPrintId);
                break;
            case Consts.MODE_HSJJ:
                //交接报表
                mIntent.putExtra("startDate", mStartDate);
                mIntent.putExtra("pyFlag", mPyFlag);
                break;
        }
        startActivity(mIntent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (event.getKeyCode()) {
            case 19:
                //上
                position = mLayoutManager.findFirstVisibleItemPosition();
                ZLog.e(position + "=================");
                if (mReports == null)
                    break;
                if (position >= 0) {
                    --position;
                    MoveToPosition(mLayoutManager, mRvReport, position);
                }
                break;
            case 20:
                //下
                position = mLayoutManager.findFirstVisibleItemPosition();
                ZLog.e(position + "=================");
                if (mReports == null)
                    break;
                if (position < mReports.size() - 1 && !(mLayoutManager.findLastVisibleItemPosition() > mReports.size() - 1)) {
                    ++position;
                    MoveToPosition(mLayoutManager, mRvReport, position);
                }
                break;
        }
        if (KeyEvent.KEYCODE_ENTER == event.getKeyCode() && mMode != Consts.MODE_BB) {
            intent(mMode);
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager       设置RecyclerView对应的manager
     * @param mRecyclerView 当前的RecyclerView
     * @param n             要跳转的位置
     */
    public void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {

        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();

        ZLog.e(firstItem + "========" + lastItem + "======" + position);
        if (n <= firstItem) {
            if (n != -1) {
                mRecyclerView.scrollToPosition(n);
            }
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }
}
